<template>
  <div>
    <el-form
      :rules="rules"
      :model="loginForm"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="loginForm.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loginForm: {
        username: "admin",
        password: "123456",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 11,
            message: "长度在 3 到 11 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 3,
            max: 16,
            message: "长度在 5 到 16 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    login() {
      // console.log(this.loginForm);
      //判断输入框是否又内容
      this.$refs.ruleForm.validate((valid) => {
        // console.log(valid);
        //有内容的运行条件
        if (valid) {
          //发起Axios请求
          this.$req.post("/login", this.loginForm)
            .then((result) => {
              // console.log(result);
              //当请求状态时200（成功时）运行的代码
              if (result.data.meta.status == 200) {
                //储存本地
                var data = result.data.data
                  this.$store.commit('userchang',data)
                // localStorage.setItem("userinfo", JSON.stringify(data));
                
                //弹出登录成功的提示
                this.$message({
                  showClose: true,
                  message: "恭喜你，登陆成功",
                  type: "success",
                });
                //成功之后跳转的地址
                this.$router.push('/home')
              } else {
                //错误的情况下提示的错误信息
                this.$message.error(result.data.meta.msg);
              }
            });
        } else {
          //如果没有输入内容提示的信息
          alert("请输入正确格式的用户名或者密码");
          return false;
        }
      });
    },
  },
};
</script>

<style>
</style>